package com.springboot.study.consumer;
import com.rabbitmq.client.Channel;
import com.springboot.study.config.RabbitConfigOrder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
public class OrderConsumer {
    @RabbitListener(queues = RabbitConfigOrder.ORDER_QUEUE)
    public void processOrder(String message, Channel channel,
                             @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            System.out.println("处理订单：" + message);

            // 模拟业务处理
            Thread.sleep(1000);

            // 手动确认
            channel.basicAck(deliveryTag, false);
            System.out.println("订单处理完成，已确认消息：" + message);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                // 处理异常，消息重新入队
                channel.basicNack(deliveryTag, false, true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

